const crypto = require('crypto');
const {
	$_ULOG,
} = require('../logger/logger');

const headersConf = global.sysConfig.headers;

module.exports = function(req, res, next) {
	let path = req.path
		// let startReg = /^(\/images\/|\/css\/|\/build\/|\/js\/|\/xmstyle\/|\/ssstyle\/)/;
	let endReg = /(\.png|\.jpg|\.jpeg|\.gif|\.map|\.js|\.jsx|\.css|\.html)$/
	if (!endReg.test(path)) {
		$_ULOG.call(req, `---请求进入-[${path}]--filterHeaders.js---`)
	}
	let headers = req.headers || {};
	/**
	 * 手机厂商接口 请求头md5验证
	 * 时间戳: timeStamp
	 * 校验码: identityCode === > (97 + md5(key + timeStamp))
	 * @param  {[type]} 
	 * @return {[type]} 
	 */
	// if(headersConf.md5.validate && (req.path in headersConf.md5)){
	// 	var pathMd5 = headersConf.md5[req.path],
	// 		identityCode = headers[pathMd5.encryptionCode.toLowerCase()] && headers[pathMd5.encryptionCode.toLowerCase()].toUpperCase(),
	// 		md5 = crypto.createHash('md5'),
	// 		accessToken = '', md5Args = '';
	// 	for(var arg of pathMd5.args){
	// 		md5Args += headers[arg.toLowerCase()];
	// 	}
	// 	accessToken = pathMd5.pre + md5.update(pathMd5.key + md5Args).digest('hex').toUpperCase();
	// 	if(accessToken != identityCode){
	// 		res.type("json").send({
	// 			status: "非法请求",
	// 			statusCode: 500
	// 		});
	// 		return;
	// 	}
	// }
	if (req.path in headersConf.path) {
		let headerPath = headersConf.path[req.path];
		for (let h in headerPath) {
			req.headers[h] = headerPath[h];
		}
	}
	if (req.path.indexOf("/payresult/wxpay/async") > -1) {
		req.headers["content-type"] = "application/x-www-form-urlencoded"
	}
	let userAgent = req.headers && req.headers['user-agent'] || ''
	if (userAgent.match(/MicroMessenger/i)) {
		res.isWXBrowser = true
	}
	next();
}